package com.zf.museum.service.impl;

import com.zf.museum.model.*;
import com.zf.museum.repository.UserRepository;
import com.zf.museum.repository.WrongRepository;
import com.zf.museum.service.WrongService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

@Service
public class WrongServiceImpl implements WrongService{

    @Autowired
    private WrongRepository wrongRepository;
    @Autowired
    private UserRepository userRepository;

    @Override
    public void addMulti(MultiChoices multiChoices, String openId) {

        Wrong wrong = getWrong(openId);
        Set<MultiChoices> set = wrong.getMultiChoices();
        set.add(multiChoices);
        wrong.setMultiChoices(set);
        wrongRepository.saveAndFlush(wrong);
    }

    @Override
    public void addSingle(SingleChoice singleChoice, String openId) {

        Wrong wrong = getWrong(openId);
        Set<SingleChoice> set = wrong.getSingleChoices();
        set.add(singleChoice);
        wrong.setSingleChoices(set);
        wrongRepository.saveAndFlush(wrong);
    }

    @Override
    public void addTfng(Tfng tfng, String openId) {

        Wrong wrong = getWrong(openId);
        Set<Tfng> set = wrong.getTfngs();
        set.add(tfng);
        wrong.setTfngs(set);
        wrongRepository.saveAndFlush(wrong);
    }

    @Override
    public Wrong getWrong(String openId) {

        User user = userRepository.getUserByOpenId(openId);
        Wrong wrong = wrongRepository.getWrongByUser(user);
        if (wrong == null) {
            wrong = new Wrong();
            Set<MultiChoices> multiChoices = new HashSet<>();
            Set<SingleChoice> singleChoices = new HashSet<>();
            Set<Tfng> tfngs = new HashSet<>();
            wrong.setUser(user);
            wrong.setMultiChoices(multiChoices);
            wrong.setSingleChoices(singleChoices);
            wrong.setTfngs(tfngs);
        }
        return wrong;
    }
}
